{extend name="../../base/view/common/base" /}
<!-- 主体 -->
{block name="body"}
<div id="tip_modal">
    <form class="layui-form p-4">
        <h3 class="pb-3">功能菜单/节点</h3>
        <table class="layui-table layui-table-form">
            <tr>
                <td class="layui-td-gray">业务类型<font>*</font>
                </td>
                <td>
                    <select name="type" lay-filter="materRial" id="materRial" lay-verify="" lay-search>
                        {volist name='typeList' id='tl'}
                        <option value="{$tl}" title="{$tl}" } {if isset($detail.type) &&$detail.type==$tl} selected {/if}>{$tl}</option>
                        {/volist}
                    </select>
                </td>
                <td class="layui-td-gray">收货单位
                </td>
                <td>
                    <select name="punter_id" id="" lay-search lay-verify="">
                        <option value="">请选择</option>
                        {volist name='punterList' id='pl'}
                        <option value="{$pl.id}" {if isset($detail.punter_id) &&$detail.punter_id==$pl.id} selected {/if}>{$pl.name}</option>
                        {/volist}
                    </select>
                </td>
            </tr>

            <tr>
                <td class="layui-td-gray" >打印公司名称<font>*</font>
                </td>
                <td>
                    <select name="printCompany" >
                        {volist name='printCompany' id='pc'}
                        <option value="{$pc}" {if isset($detail.printCompany)&&$detail.printCompany==$pc } selected {/if}>{$pc}</option>
                        {/volist}
                    </select>

                </td>
                <td class="layui-td-gray">订单码<font>*</font></td>
                <td>
                    <select name="oCode"  {if $id} disabled {/if} >
                        {foreach $orCode as $ork=>$orv}
                        <option value="{$ork}" {if isset($detail.oCode)&&$detail.oCode==$ork} selected{/if}>{$orv}</option>
                        {/foreach}
                    </select>
                </td>
            </tr>
            <tr>
                <td class="layui-td-gray">出库时间<font>*</font>
                </td>
                <td>
                    <input type="text" class="layui-input" value="{$detail.outTime|default=$defalutTime}" readonly name="outTime" id="outTime" placeholder="选择时间"
                           required>
                </td>
                <td class="layui-td-gray">状态<font>*</font>
                </td>
                <td>
                    <select name="status" disabled>
                        {foreach [['id'=>1,'name'=>'草稿'],['id'=>2,'name'=>'已确认']] as $st}
                        <option value="{$st.id}" {if isset($detail.status)&&$detail.status==$st.id } selected {/if}>{$st.name}</option>
                        {/foreach}
                    </select>

                </td>

            </tr>
            <tr>
                <td>出库人</td>
                <td>
                    <span>{$detail.username|default=''}</span>
                </td>
                <td>单据编号</td>
                <td>
                    <input type="text" {if !$id} disabled readonly {/if} name="orderNum" class="layui-input" maxlength="30" value="{$detail.orderNum|default=''}" required >
                </td>
            </tr>

            <tr>
                <td colspan="6"><h3>明细</h3></td>
            </tr>
            <tr>
                <td colspan="6">
                    {if !isset($detail.status)||$detail.status==1}
                    <a href="javascript:" id="a" data-modal="{:url('addMx')}" class="layui-btn layui-btn-primary">选择物料</a>
                    {/if}
                </td>
            </tr>
            <table class="layui-table tableMany">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>品牌</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>仓库</th>
<!--                    <th>库位</th>-->
                    <th>数量</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
                </thead>
                {if isset($mxList)}
                <tbody id="mxTbdy">
                {volist name='mxList' id='ml' key='k'}
                <tr>
                    <td><span class="xuhao">{$k}</span>
                        <input type="hidden" name="mxid[]" value="{$ml.id}">
                        <input type="hidden" name="material_id[]" value="{$ml.material_dossier_id}">
                        <input type="hidden" name="oldNum[]" value="{$ml.haveNum}">
                        <input type="hidden" name="warehouse_id[]" value="{$ml.warehouse_id}">
                        <input type="hidden" name="locator[]" value="{$ml.locator}">
                    </td>

                    <td>{$ml.bar_code}</td>
                    <td>{$ml.mdName}</td>
                    <td>{$ml.mdBrand}</td>
                    <td>{$ml.specs}</td>
                    <td>{$ml.unit}</td>
                    <td>
                        {$ml.warehouseName}
                    </td>
<!--                    <td>-->
<!--                        {$ml.locatorName}-->
<!--                    </td>-->
                    <td><input type="text" value="{$ml.num}" class="layui-input " maxlength='9' required
                               lay-verify="required" onkeyup="digitalFiltering(this,2)" placeholder="请输入数量"
                               autocomplete="off" min="0" max="999999" name="num[]"></td>

                    <td>
                        <input type="text" value="{$ml.o_remark}" class="layui-input " placeholder="请输入备注" name="o_remark[]">
                    </td>
                    <td>
                        {if !isset($detail.status)||$detail.status==1}
                        <a href="javascript:" class="layui-btn layui-btn-xs layui-btn-danger"
                           onclick="delMx('{$ml.id}',this)">删除</a>
                        {/if}
                    </td>
                </tr>
                {/volist}
                </tbody>
                {else}
                <tbody id="mxTbdy">
                </tbody>
                {/if}

            </table>
        </table>
        <div class="py-3">
            <input type="hidden" name="id" value="{$id}">
            {if !isset($detail.status)||$detail.status==1}
            <button class="layui-btn layui-btn-normal" type="button" id="sub" lay-submit="" lay-filter="webform1">保存 </button>
           {/if}
            {if isset($detail.status)&&$detail.status==1}
            <button type="button" class="layui-btn layui-btn-normal" onclick="onSure()">确认</button>
            {/if}
            {if isset($detail.status)&&$detail.status==2}
            <button type="button" class="layui-btn layui-btn-danger" onclick="onCancel()">撤销</button>
            {/if}
        </div>
    </form>
</div>

{/block}
<!-- /主体 -->
{block name="script"}
<script>

    const moduleInit = ['tool'];

    let isSub = 2;
    function gouguInit() {
        var form = layui.form, tool = layui.tool;
        //监听提交
        form.on('submit(webform1)', function (data) {
            let callback = function (e) {
                isSub = 2;
                layer.msg(e.msg);
                if (e.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            }
            if (isSub == 2) {
                isSub = 1
                tool.post("{:url('add')}", data.field, callback);
            }
            return false;
        });

        // layui.use(['form'], function () {
        //     var form = layui.form;
        //     form.render();
        // });
        form.on('select(materRial)', function (data) {
            var selectedTitle = '';
            $('#materRial option').each(function () {
                if ($(this).val() == data.value) {
                    selectedTitle = $(this).attr('title');
                }
            });
            console.log('ttt', selectedTitle)
            $('#spces').text(selectedTitle)
        }); // select(lay-filter属性的值)
        //动态获取联动
        form.on('select(warehouse_id)', function (data) {
            var mxIndex = 1;
            var sid= $(data.elem).attr('id')
            var wid=data.value;
            $('#'+sid+' option').each(function () {
                if ($(this).val() == data.value) {
                    mxIndex = $(this).attr('title');
                }
            });
            $("#locator_"+mxIndex+"").empty();
            var optionStr='';
            if (wid!=''){
              $.ajax({
                  url:'/home/api/getWarHoseDetail',
                  type:'post',
                  dataType:'json',
                  data:{id:wid},
                  success:function (res) {
                      if (res.code==0){
                          let data=res.data;
                          for(var i=0;i<data.length;i++){
                              optionStr+=" <option value='"+data[i].id+"'>"+data[i].name+"</option>";
                          }
                      }else {
                          optionStr+=" <option value=''>暂无数据</option>";
                      }
                      $("#locator_"+mxIndex+"").append(optionStr);
                      form.render();
                  }

              })
            }else {
                optionStr+=" <option value=''>请选择仓库</option>";
                $("#locator_"+mxIndex+"").append(optionStr);
                form.render();
            }


        }); // select(lay-filter属性的值)
        //弹窗
        var treeTable = layui.table, form = layui.form;
        var tableIns = treeTable.render({
            elem: '#mxTable'
            , url: "{:url('addMx')}"
            , method: 'post'
            , toolbar: '#toolbarDemo',
            defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {type: 'checkbox', fixed: 'left'},
                {fixed: 'left', field: 'id', title: 'ID', unresize: true, hide: true}
                // ,{field: 'id', width: 80, title: 'ID号', align: 'center'}
                , {field: 'bar_code', title: '编码'}
                , {field: 'mdName', title: '名称'}
                , {field: 'mdBrand', title: '品牌'}
                , {field: 'specs', title: '规格型号'}
                , {field: 'unit', title: '单位'}
                , {field: 'warehouseName', title: '仓库'}
                // , {field: 'locatorName', title: '库位'}
                , {field: 'num', title: '库存数量'}
                // , {field: 'sendNum', title: '出库数量'}
            ]]
            , page: true
        });
        //监听搜索提交
        form.on('submit(webform)', function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });
        //表头工具栏事件
        treeTable.on('toolbar(mxTable)', function (obj) {
            var checkStatus = treeTable.checkStatus(obj.config.id);
            console.log(checkStatus)
            switch (obj.event) {
                case 'add':
                    break;
                case 'subt':
                    var data = checkStatus.data;
                    var ids = []
                    if (data.length) {
                        data.forEach(function (value, index) {
                            ids.push(value)
                        })
                        saveAddMx(ids)
                        layer.close(layTip)

                    } else {
                        layer.msg('请选择数据');
                    }

                    break;
                case 'import':

                    break;

            }
            ;
        })
        laydate.render({
            elem: '#outTime'
            , type: 'date',
        });
    }
</script>
<script>
    function saveAddMx (ojb) {
        var lastListItem = $('.tableMany tr:last');
        let aa = $(lastListItem).find(".xuhao")
        let len = $(aa).text()
        console.log('leng:', len)
        if (!parseInt(len)) {
            len = 0;
        }
        let index = parseInt(len) + 1;
        let str = '';
        for (var i = 0; i < ojb.length; i++) {
            str += "  <tr>\n" +
                "                <td> <span class=\"xuhao\">" + index + "</span> <input type=\"hidden\" name=\"mxid[]\" value=\"\">" +
                "<input type=\"hidden\" name=\"material_id[]\" value=\"" + ojb[i].mdId + "\">" +
                "<input type=\"hidden\" name=\"warehouse_id[]\" value=\"" + ojb[i].wId + "\">" +
                "<input type=\"hidden\" name=\"locator[]\" value=\"" + ojb[i].locator + "\">" +
                "</td>\n" +
                "                <td> " + ojb[i].bar_code + " </td>\n" +
                "                <td> " + ojb[i].mdName + " </td>\n" +
                "                <td> " + ojb[i].mdBrand + " </td>\n" +
                "                <td>" + ojb[i].specs + " </td>\n" +
                "                <td>" + ojb[i].unit + " </td>\n" +
                "                <td>"+ojb[i].warehouseName+"</td>\n" +
                // "                <td>"+ojb[i].locatorName+"</td>\n" +
                "                <td>\n" +
                "                    <input type=\"text\" value='"+ojb[i].num+"' class=\"layui-input \" maxlength='9' required lay-verify=\"required\" onkeyup=\"digitalFiltering(this,2)\" placeholder=\"请输入数量\" autocomplete=\"off\" min=\"0\" max=\"999999\" name=\"num[]\">\n" +
                "                    <input type=\"hidden\" value='"+ojb[i].num+"' class=\"layui-input \"  name=\"oldNum[]\">\n" +
                "                </td>\n" +
                " <td>\n" +
                "     <input type=\"text\" value='' class=\"layui-input \" placeholder=\"请输入备注\" name=\"o_remark[]\">\n" +
                "                    </td>" +
                "                <td>\n" +
                "                    <a href=\"javascript:\" class='layui-btn layui-btn-danger layui-btn-xs' onclick='removetr(this)'>删除</a>\n" +
                "                </td>\n" +
                "            </tr>";
            index++;
        }
        $("#mxTbdy").append(str)
        layui.use(['form'], function () {
            var form = layui.form;
            form.render();
        });
    }

    function removetr(e) {
        $(e).parent().parent().remove()
    }

    function delMx(id = '', e) {
        if (id == '') {
            layer.msg('请选择数据')
            return;
        }
        $.ajax({
            url: "{:url('removeMx')}",
            type: 'post',
            dataType: 'json',
            data: {id: id},
            success: function (res) {
                if (res.code != 0) {
                    layer.msg(res.msg)
                } else {
                    removetr(e)
                }
            },
            error(e) {
                layer.msg('网络错误，请稍后')
            }
        })
    }

    let is_sure=2;
    function onSure() {
        let id="{$id}";
        if (id==0){
            layer.msg('操作有误');
            return;
        }
        if (is_sure==1){
            return;
        }
        is_sure=1;
        $.ajax({
            url:"{:url('onSure')}",
            type:'post',
            dataType:'json',
            data:{id:id},
            success:function (res) {
                is_sure=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_sure=2
            }
        })
    }
    //
    // let is_cancel=2;
    // function onCancel() {
    //     let id="{$id}";
    //     if (is_cancel==1){
    //         return;
    //     }
    //     is_cancel=1;
    //     $.ajax({
    //         url:"{:url('onCancel')}",
    //         type:'post',
    //         dataType:'json',
    //         data:{id:id},
    //         success:function (res) {
    //             is_cancel=2;
    //             layer.msg(res.msg)
    //             if (res.code == 0) {
    //                 setTimeout(function () {
    //                     parent.parent.location.reload();
    //                 }, 1000);
    //             }
    //         },
    //         error(e){
    //             layer.msg('网络错误，请稍后重试')
    //             is_cancel=2
    //         }
    //     })
    // }

    let is_cancel=2;
    function onCancel() {
        let id="{$id}";
        if (is_cancel==1){
            return;
        }
        is_cancel=1;
        $.ajax({
            url:"{:url('onCancel')}",
            type:'post',
            dataType:'json',
            data:{id:id},
            success:function (res) {
                is_cancel=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_cancel=2
            }
        })
    }
</script>
{/block}
<!-- /脚本 -->